const { pool: db } = require('../config/database.js')

/**
 * 获取所有城市信息
 */
exports.getAllCities = async (req, res) => {
  try {
    const [rows] = await db.query('SELECT Name, CountryCode FROM city')
    res.status(200).json({
      success: true,
      data: rows,
      total: rows.length,
    })
  } catch (error) {
    console.error('获取城市信息失败:', error)
    res.status(500).json({
      success: false,
      message: '获取城市信息失败',
      error: error.message,
    })
  }
}

/**
 * 根据国家代码获取城市信息
 */
exports.getCitiesByCountry = async (req, res) => {
  try {
    const countryCode = req.params.countryCode
    const [rows] = await db.query('SELECT Name, CountryCode FROM city WHERE CountryCode = ?', [countryCode])

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: `未找到国家代码为 ${countryCode} 的城市`,
      })
    }

    res.status(200).json({
      success: true,
      data: rows,
      total: rows.length,
    })
  } catch (error) {
    console.error('获取城市信息失败:', error)
    res.status(500).json({
      success: false,
      message: '获取城市信息失败',
      error: error.message,
    })
  }
}

/**
 * 根据城市名称搜索城市
 */
exports.searchCities = async (req, res) => {
  try {
    const { name } = req.query
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '请提供城市名称',
      })
    }

    const [rows] = await db.query('SELECT Name, CountryCode FROM city WHERE Name LIKE ?', [`%${name}%`])
    res.status(200).json({
      success: true,
      data: rows,
      total: rows.length,
    })
  } catch (error) {
    console.error('搜索城市失败:', error)
    res.status(500).json({
      success: false,
      message: '搜索城市失败',
      error: error.message,
    })
  }
}
